/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Main;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 *
 * @author Daniel
 */
public class TremConect implements Runnable{
    private ServerSocket socket;
    private Socket peer;
    private final DTrem trem;
    private Thread t;
    private Controller c;

    /**
     *
     * @param trem
     */
    public TremConect(DTrem trem) {
        this.trem = trem;
        try {
            this.socket = new ServerSocket(1337);
        } catch (IOException ex) {
            System.out.println("socket error");
        }
    }
    @Override
    public void run() {
        /*O trem recebe uma conexão e interrompe a possibilidade de
        novas tentativas de conexão. Cria as threads de envio e entrada de dados
        */
        try {
            peer = socket.accept();
            trem.setTremNumber(1);
            c.setIpText(peer.getInetAddress().getHostAddress());
            c.stopConections();
            Send s = new Send(trem, new PrintStream(peer.getOutputStream()));
            t = new Thread(s);
            t.start();
            peer = socket.accept();
            Receive r = new Receive(trem, new Scanner(peer.getInputStream()));
            t = new Thread(r);
            t.start();
        } catch (IOException ex) {
            System.out.println("conection error");
        }

        
    }

    /**
     *
     * @param ip
     * @return
     */
    public boolean conect(String ip){
        /*O trem se conecta a outro trem. Cria as threads de envio e entrada de 
        dados.*/
        try {
            peer = new Socket(ip, 1337);
            trem.setTremNumber(2);
            Receive r = new Receive(trem, new Scanner(peer.getInputStream()));
            t = new Thread(r);
            t.start();
            peer = new Socket(ip,1337);
            Send s = new Send(trem, new PrintStream(peer.getOutputStream()));
            t = new Thread(s);
            t.start();
            return true;
            
            
            
        } catch (UnknownHostException ex) {
            System.out.println("conection error");
            return false;
        } catch (IOException ex) {
            System.out.println("conection error");
            return false;
        }
    }

    /**
     *
     * @param controller
     */
    public void setC(Controller controller) {
        this.c = controller;
    }
    
    
}
